package com.mediacloud.app.newsmodule.activity

import android.content.Intent
import android.media.MediaMetadata
import android.media.session.PlaybackState
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chinamcloud.audioserver.APSLifecycleKit
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.model.activity.SwipeBackFragmentActivity
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.LiveProgramListReciver
import com.mediacloud.app.model.news.ProgramListItem
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast
import com.mediacloud.app.newsmodule.interfaces.DataInitCall
import com.mediacloud.app.newsmodule.utils.ShareGridPopUtils
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.newsmodule.utils.VideoLiveProgramListInvoker
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import kotlinx.android.synthetic.main.chat_live_progress_activity.*
import tv.danmaku.ijk.media.player.IMediaPlayer
import java.text.SimpleDateFormat
import java.util.*

class ChatLiveProgressListActivity : SwipeBackFragmentActivity(), DataInitCall {
    override fun onInitSelect(position: Int) {
        val data: MutableList<ProgramListItem>? = programListItems[position].programList
        proAdapter?.data = data
        proAdapter?.notifyDataSetChanged()
        data?.forEachIndexed { index, programListItem ->
            if (ProgramListItem.getItemState(programListItem) == ProgramListItem.GuideItemState.LIVE) {
                programList?.smoothScrollToPosition(index)
            }
        }

    }

    var articleItem: ArticleItem? = null
    var programListCallBack: ProgramListCallBack? = null
    var liveProgramListInvoker: VideoLiveProgramListInvoker? = null
    var programListItems: List<LiveProgramListReciver.ProgramWeekItem> = ArrayList()
    private var dateAdapter: ChatLiveProgramDateAdapter? = null
    private var proAdapter: ChatLiveProgramListAdapter? = null
    var startLong = 0L
    var endLong = 0L

    var apsKit: APSLifecycleKit? = null
    var shareWrap:ShareWrap?=null
    override fun getLayoutResID(): Int {
        return R.layout.chat_live_progress_activity
    }

    override fun getStatusBarColor(): Int {
        return intent.extras!!.getInt("COLOR")
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        articleItem = intent.extras?.getParcelable("data")
        var color = intent.extras!!.getInt("COLOR")
        startLong = intent.extras!!.getLong("START_LONG")
        endLong = intent.extras!!.getLong("END_LONG")
        bgImage.setBackgroundColor(color)
        logo.load(articleItem?.logo, 12)
        playingLogo.load(articleItem?.logo, 12)

        audioTitle.text = articleItem?.title
        audioTitleB.text = articleItem?.title
        anchor.text = "主播：" + articleItem?.Author
        summary.text = articleItem?.summary
        source.text = "来源：" + articleItem?.referName
        sourceB.text = "来源：" + articleItem?.referName


        programListCallBack = ProgramListCallBack()
        liveProgramListInvoker = VideoLiveProgramListInvoker(programListCallBack)
        liveProgramListInvoker?.getLiveVideoProgramList(articleItem)
        backBtn.setOnClickListener { finish() }


        programDateList.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(this, false)
        dateAdapter = ChatLiveProgramDateAdapter(this)
        dateAdapter?.call = this
        programDateList?.adapter = dateAdapter
        dateAdapter!!.setItemClickListener { index, _, _ ->
            if (index != dateAdapter!!.selectedIndex) {

                dateAdapter!!.selectedIndex = index
                proAdapter?.data = programListItems[index].programList
                proAdapter?.startLong = startLong
                proAdapter?.endLong = endLong
                proAdapter?.notifyDataSetChanged()
            }
        }
        programList.layoutManager = LinearLayoutManager(this)
        proAdapter = ChatLiveProgramListAdapter(this, AppFactoryGlobalConfig.getAppServerConfigInfo(this).mainColor)
        proAdapter?.startLong = startLong
        proAdapter?.endLong = endLong
        programList.adapter = proAdapter
        proAdapter!!.setItemClickListener { index, _, _ ->
            val item = proAdapter!!.getItem(index)

            //如果选择的是空 或者  选中了当前的 或者 是即将播放的就不处理
            if (ProgramListItem.GuideItemState.COMING_SOON == ProgramListItem.getItemState(item)) {
                ToastUtil.show(this, "还没到播放时间")
                return@setItemClickListener
            }
            val intent = Intent()
            intent.action = LiveReplayBroadcast.PlayAction
            intent.putExtra("data", item)
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent)//发送广播  通知回看或是从回看切到直播
            finish()
        }

        apsKit = APSLifecycleKit(this, "${articleItem?.id}", null, object : APSLifecycleKit.APSCallback() {

            override fun onBufferingUpdate(mediaPlayer: IMediaPlayer?, percent: Int) {

            }

            override fun onCompletion(mediaPlayer: IMediaPlayer?) {
            }

            override fun onMetadataChanged(metadata: MediaMetadata?) {
                super.onMetadataChanged(metadata)
            }

            override fun onPlaybackStateChanged(state: PlaybackState?) {
                super.onPlaybackStateChanged(state)
                when (state!!.state) {
                    PlaybackState.STATE_NONE ,PlaybackState.STATE_STOPPED,PlaybackState.STATE_PAUSED-> image_toggle_audio_play.setImageResource(R.drawable.chat_audio_play)
                    PlaybackState.STATE_PLAYING -> image_toggle_audio_play.setImageResource(R.drawable.chat_audio_pause)
                    PlaybackState.STATE_SKIPPING_TO_NEXT -> {
                    }
                    PlaybackState.STATE_SKIPPING_TO_PREVIOUS -> {
                    }
                    PlaybackState.STATE_FAST_FORWARDING -> {
                    }
                    PlaybackState.STATE_REWINDING -> {
                    }
                    PlaybackState.STATE_ERROR -> com.utils.ToastUtil.showToastCenter(this@ChatLiveProgressListActivity, "出错了", Toast.LENGTH_SHORT)
                }
            }

            override fun onPrepared(mediaPlayer: IMediaPlayer?) {

            }
        })



        image_toggle_audio_play.setOnClickListener {
            apsKit?.toggle()
        }

        shareWrap = ShareWrap(this,false)
        shareWrap?.setShowFunction(true)
        shareWrap?.init(articleItem, CatalogItem())
        findViewById<View>(R.id.shareBtn).setOnClickListener {
            shareWrap?.show(it)
           // ShareGridPopUtils.show(this, articleItem, CatalogItem(), false, false, window.decorView)
        }
    }

    inner class ProgramListCallBack : DataInvokeCallBack<LiveProgramListReciver> {
        override fun success(data: LiveProgramListReciver) {
            programListItems = data.programListItems
            if (programListItems.isEmpty()) {
                ToastUtil.showCustomView(this@ChatLiveProgressListActivity, R.string.no_audioprogramlist)
                return
            }
            dateAdapter?.data = data.programListItems
            val sdf = SimpleDateFormat("yyyyMMdd", Locale.CHINA)

            val day = if (startLong > 0L) {
                sdf.format(startLong)
            } else {
                sdf.format(System.currentTimeMillis())
            }
            dateAdapter?.setSelectedDay(day)
        }

        override fun fault(data: Any) {
            Log.w(TAG, "get audio live programlist failed:$data")
        }
    }


}